package com.ruicar.afs.cloud.workflow.greatwall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.datasync.componts.SyncHelper;
import com.ruicar.afs.cloud.workflow.api.cachebean.FlowMappingInfo;
import com.ruicar.afs.cloud.workflow.api.constant.FlowConstant;
import com.ruicar.afs.cloud.workflow.greatwall.entity.AfsGreatWallWorkflowMappingInfo;
import com.ruicar.afs.cloud.workflow.greatwall.mapper.AfsGreatWallWorkFlowMappingInfoMapper;
import com.ruicar.afs.cloud.workflow.greatwall.service.AfsGreatWallWorkflowMappingInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AfsGreatWallWorkflowMappingInfoImpl extends ServiceImpl<AfsGreatWallWorkFlowMappingInfoMapper, AfsGreatWallWorkflowMappingInfo> implements AfsGreatWallWorkflowMappingInfoService {
    @Override
    public void publishFlowMapping() {
        try {
            List<FlowMappingInfo> mappingInfoList = this.list()
                    .stream()
                    .map(afsMapping -> FlowMappingInfo.builder().autoTryResolverType(Arrays.asList(afsMapping.getAutoExceptionProcess().split(","))).afsConfigKey(afsMapping.getAfsFlowKey()).flowName(afsMapping.getGreatWallServiceName()).serviceId(afsMapping.getGreatWallServiceId()).build())
                    .collect(Collectors.toList());
            JSONObject object = new JSONObject();
            object.put(FlowConstant.FLOW_MAPPING_SYNC_KEY.getKey(), mappingInfoList);
            SyncHelper.publishParams(FlowConstant.FLOW_MAPPING_SYNC_KEY, object);
        } catch (Exception e) {
            log.error("流程映射同步失败", e);
            throw new AfsBaseException(CommonConstants.FAIL, "流程配置同步失败，请再次保存");
        }
    }

    @Override
    public AfsGreatWallWorkflowMappingInfo queryMappingByServiceId(String serviceId) {
        return this.baseMapper.selectOne(Wrappers.<AfsGreatWallWorkflowMappingInfo>lambdaQuery().eq(AfsGreatWallWorkflowMappingInfo::getGreatWallServiceId, serviceId));
    }

    @Override
    public AfsGreatWallWorkflowMappingInfo queryMappingByAfsKey(String afsKey) {
        return this.baseMapper.selectOne(Wrappers.<AfsGreatWallWorkflowMappingInfo>lambdaQuery().eq(AfsGreatWallWorkflowMappingInfo::getAfsFlowKey, afsKey));
    }
}
